package com.hr.剑指offer.work1;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 周恒哲
 * @date 2020/06/17
 * 哈希表统计法
 **/
public class 面试题39_数组中出现次数超过一半的数字 {
    //排序法
    public static int majorityElement(int[] nums) {
        Arrays.sort(nums);
        int len=(nums.length+1)/2;
        return nums[len];
    }
    //哈希表
    public static int majorityElement2(int[] nums) {
        Map<Integer, Integer> map=new HashMap<>();
        int res=0;
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else {
                map.put(nums[i], 1);
            }
            if (map.get(nums[i])>=(nums.length/2)){
                res=nums[i];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(面试题39_数组中出现次数超过一半的数字.majorityElement2(new int[]{
                1, 2, 3, 2, 2, 2, 5, 4, 2
        }));
    }

}
